﻿using log4net;
using SuperFx;
using SuperMoney.Datas;
using SuperMoney.Datas.DbModels;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SuperMoney.AdPlatformCallback.Controllers
{
	/// <summary>
	/// 有米积分墙服务器端回调控制器。
	/// </summary>
	public class YoumiController : Controller
	{
		const string adPlatform = "youmi";

		static readonly string mrm_ios_secret = ConfigurationManager.AppSettings[adPlatform + "-mrm-ios-secret"];
		static readonly string mrm_android_secret = ConfigurationManager.AppSettings[adPlatform + "-mrm-android-secret"];

		static readonly string mrc_ios_secret = ConfigurationManager.AppSettings[adPlatform + "-mrc-ios-secret"];
		static readonly string mrc_android_secret = ConfigurationManager.AppSettings[adPlatform + "-mrc-android-secret"];

		// 百宝箱iOS的密钥
		static readonly string bbx_ios_secret = ConfigurationManager.AppSettings[adPlatform + "-bbx-ios-secret"];
		// 百宝箱Android的密钥
		static readonly string bbx_android_secret = ConfigurationManager.AppSettings[adPlatform + "-bbx-android-secret"];

		//
		// GET: /Youmi/Android

		public ActionResult Android(string order, string app, string ad, string user, string device, string chn, int? points, int? time, string sig)
		{
			return this.Android_MRM(order, app, ad, user, device, chn, points, time, sig);
		}

		public ActionResult Android_MRM(string order, string app, string ad, string user, string device, string chn, int? points, int? time, string sig)
		{
			return this._Android(mrm_android_secret, order, app, ad, user, device, chn, points, time, sig);
		}

		public ActionResult Android_MRC(string order, string app, string ad, string user, string device, string chn, int? points, int? time, string sig)
		{
			return this._Android(mrc_android_secret, order, app, ad, user, device, chn, points, time, sig);
		}

		public ActionResult Android_BBX(string order, string app, string ad, string user, string device, string chn, int? points, int? time, string sig)
		{
			return this._Android(bbx_android_secret, order, app, ad, user, device, chn, points, time, sig);
		}

		ActionResult _Android(string secret, string order, string app, string ad, string user, string device, string chn, int? points, int? time, string sig)
		{
			string str = order + "||" + app + "||" + user + "||" + chn + "||" + ad + "||" + points;
			str = secret + "||" + str;
			string md5 = Md5Hash.Compute(str);
			string sig_local = md5.Substring(12, 8);
			// 签名验证
			if (sig == sig_local)
			{// 通过
				try
				{
					if (!points.HasValue) points = 0;
					if (!time.HasValue) time = 0;
					AdRecordService.Instance.Create(adPlatform, order, null, time.Value, device, null, ad, chn, points.Value, 0, app, "android", user);
				}
				catch (Exception<AdRecordExistsExceptionArgs> ex)
				{
					LogManager.GetLogger("android").Error(order + "有米广告记录已存在", ex);
					HttpContext.Response.StatusCode = 403;
				}
			}
			else
			{// 失败
				LogManager.GetLogger("android").Error(Request.Url + "签名验证不通过");
				HttpContext.Response.StatusCode = 400;
			}

			return new EmptyResult();
		}

		//
		// GET: /Youmi/iOS

		public ActionResult iOS(string order, string app, string ad, string adid, string user, string device, string chn, decimal? price, int? points, int? time, string sig, string sign)
		{
			return this.iOS_MRM(order, app, ad, adid, user, device, chn, price, points, time, sig, sign);
		}

		public ActionResult iOS_MRM(string order, string app, string ad, string adid, string user, string device, string chn, decimal? price, int? points, int? time, string sig, string sign)
		{
			return this._iOS(mrm_ios_secret, order, app, ad, adid, user, device, chn, price, points, time, sig, sign);
		}

		public ActionResult iOS_MRC(string order, string app, string ad, string adid, string user, string device, string chn, decimal? price, int? points, int? time, string sig, string sign)
		{
			return this._iOS(mrc_ios_secret, order, app, ad, adid, user, device, chn, price, points, time, sig, sign);
		}

		public ActionResult iOS_BBX(string order, string app, string ad, string adid, string user, string device, string chn, decimal? price, int? points, int? time, string sig, string sign)
		{
			return this._iOS(bbx_ios_secret, order, app, ad, adid, user, device, chn, price, points, time, sig, sign);
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="secret"></param>
		/// <param name="order"></param>
		/// <param name="app"></param>
		/// <param name="ad"></param>
		/// <param name="adid"></param>
		/// <param name="user"></param>
		/// <param name="device"></param>
		/// <param name="chn"></param>
		/// <param name="price"></param>
		/// <param name="points"></param>
		/// <param name="time"></param>
		/// <param name="sig"></param>
		/// <param name="sign"></param>
		/// <returns></returns>
		ActionResult _iOS(string secret, string order, string app, string ad, string adid, string user, string device, string chn, decimal? price, int? points, int? time, string sig, string sign)
		{
			Dictionary<string, object> dict = new Dictionary<string, object>();
			foreach (var key in Request.QueryString.AllKeys)
			{
				if (key == "sign") continue;
				dict.Add(key, Request.QueryString[key]);
			}
			dict = dict.OrderBy(p => p.Key).ToDictionary(p => p.Key, p => p.Value);

			string str = null;
			foreach (var kv in dict)
			{
				string kvStr = String.Format("{0}={1}", kv.Key, kv.Value);
				if (str == null)
				{
					str = kvStr;
				}
				else
				{
					str += kvStr;
				}
			}
			str += secret;
			string sign_local = Md5Hash.Compute(str);
			// 签名验证
			if (sign == sign_local)
			{// 通过
				try
				{
					if (!price.HasValue) price = 0;
					if (!points.HasValue) points = 0;
					if (!time.HasValue) time = 0;
					DateTime adOrderTime = new DateTime(1970, 1, 1).AddSeconds(time.Value);
					AdRecordService.Instance.Create(adPlatform, order, adOrderTime, 0, device, adid, ad, chn, points.Value, price.Value, app, "ios", user);
				}
				catch (Exception<AdRecordExistsExceptionArgs> ex)
				{
					LogManager.GetLogger("ios").Error(order + "有米广告记录已存在", ex);
					HttpContext.Response.StatusCode = 403;
				}
			}
			else
			{// 失败
				LogManager.GetLogger("ios").Error(Request.Url + "签名验证不通过");
				HttpContext.Response.StatusCode = 400;
			}

			return new EmptyResult();
		}
	}
}
